package com.kitty.web.client;


import com.kitty.common.core.Scheduler2Manager;
import com.kitty.common.core.SchedulerManager;
import com.kitty.common.model.Pos;

import com.kitty.common.utils.SpringUtils;

import com.kitty.game.chat.service.ChatService;
import com.kitty.game.common.BoosTitleDeal;
import com.kitty.game.enter.Position;
import com.kitty.game.enter.ReqLoadExistedChar;
import com.kitty.game.enter.ReqMultiMoveTo;
import com.kitty.game.fight.facade.FightController;
import com.kitty.game.player.model.PlayerProfile;
import com.kitty.game.role.message.ReqLogin;
import com.kitty.game.role.message.ReqLoginAccount;
import com.kitty.game.role.message.ReqRequestLineInfo;
import com.kitty.game.role.message.RespLevelUp;
import com.kitty.game.role.model.Role;
import com.kitty.game.scene.SceneManager;
import com.kitty.game.team.service.TeamService;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.MessagePusher;
import com.kitty.mina.session.SessionProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;

import static java.lang.Thread.sleep;

@Service
@Slf4j
public class ClientRoleManage {
    @Autowired
    ClientSessionManage clientSessionManage;
    public static Boolean moveTaskAi = false;
    public static Boolean moveFightAi = false;
    public static ConcurrentMap<Integer, ConcurrentMap<Integer, IoSession>> fightAiSessionMap = new ConcurrentHashMap<>();
    public static ConcurrentMap<Integer, IoSession> moveTaskAiSessionMap = new ConcurrentHashMap<>();
    static  List<Position> movePosList = new ArrayList<>();
    static  List<Position> fightPosList = new ArrayList<>();
    static {
        {Position position = new Position((short)23,(short)109);movePosList.add(position); }//出生点
        {Position position = new Position((short)35,(short)110);movePosList.add(position); } //多闻道人
        {Position position = new Position((short)71,(short)122);movePosList.add(position); }  //王老板    升级
        {Position position = new Position((short)93,(short)119);movePosList.add(position); }   //升级   黄三
        {Position position = new Position((short)121,(short)116);movePosList.add(position); } //莲花 //多等几秒
        {Position position = new Position((short)95,(short)95);movePosList.add(position); } //赵老板   //升级
        {Position position = new Position((short)51,(short)70);movePosList.add(position); } //张老板   //多等几秒
        {Position position = new Position((short)100,(short)103);movePosList.add(position); } //赵老板 //升级
        {Position position = new Position((short)122,(short)116);movePosList.add(position); } //莲花
        {Position position = new Position((short)23,(short)109);movePosList.add(position); }//出生点

        {Position position = new Position((short)95,(short)64);fightPosList.add(position); }//天墉城出生点
        {Position position = new Position((short)25,(short)137);fightPosList.add(position); } //通灵
        {Position position = new Position((short)108,(short)18);fightPosList.add(position); }  //北斗
        {Position position = new Position((short)141,(short)17);fightPosList.add(position); }
        {Position position = new Position((short)106,(short)65);fightPosList.add(position); }
    }

    public static void main(String[] args) {
        Position position = new Position((short)51,(short)70);
        Position position2 = new Position((short)95,(short)95);

        //AiMoveCalc(position,position2);
    }

    /**
     * 登录
     */
    //@Scheduled(cron = "0 * * * * ?")
    public void loginAI(AiInfo aiInfo) {
        final int[] move = {0};
        final int[] fight = {0};
        //创建连接
        if(aiInfo.getLevel() == 0){
            clientSessionManage.createMoveSession(moveTaskAiSessionMap);
            SchedulerManager.getInstance().schedule(new Runnable() {
                @Override
                public void run() {
                    //登录移动假人
                    for (Map.Entry<Integer, IoSession> AiSession : moveTaskAiSessionMap.entrySet()) {
                        IoSession session = AiSession.getValue();
                        AiPlayer ai_player = (AiPlayer)session.getAttribute("AI_PLAYER");
                        if(ai_player == null || ai_player.getOnlineState() == 0){
                            //发送消息
                            login(session,aiInfo.getLevel());;
                            move[0] +=1;
                        }
                    }

                }
            }, 0);

        }else {
            clientSessionManage.createFightSession(fightAiSessionMap);
            //发送消息
            SchedulerManager.getInstance().schedule(new Runnable() {
                @Override
                public void run() {
                    for (Map.Entry<Integer, ConcurrentMap<Integer, IoSession>> integerConcurrentMapEntry : fightAiSessionMap.entrySet()) {
                        ConcurrentMap<Integer, IoSession> levelSessionMap = integerConcurrentMapEntry.getValue();
                        for (Map.Entry<Integer, IoSession> map : levelSessionMap.entrySet()) {
                            IoSession session = map.getValue();
                            AiPlayer ai_player = (AiPlayer)session.getAttribute("AI_PLAYER");
                            if(ai_player == null || ai_player.getOnlineState() == 0){
                                login(session,aiInfo.getLevel());;
                                fight[0] = fight[0] + 1;
                            }
                        }
                    }
                }
            }, 0);


        }
        log.info("AI登录，战斗AI："+ fight[0] +"  任务AI："+ move[0]);
    }
    public void fightAiPlayerMove(IoSession session,int roleId,int mapid,CountDownLatch latch){
        FightController fightController = SpringUtils.getBean(FightController.class);
        PlayerProfile playerProfile = (PlayerProfile)session.getAttribute(SessionProperties.PLAYER);
        Role role = SpringUtils.getRoleService().getOnlinePlayer(playerProfile.getRoleId());
        TeamService teamServer = SpringUtils.getBean(TeamService.class);
        if(teamServer.isInTeam(role)){
            return;
        }
        try{
            for (int i = 0; i < 5; i++) {
                AiPlayer ai_player = (AiPlayer)session.getAttribute("AI_PLAYER");
                if(ai_player == null || ai_player.getOnlineState() == 0){
                    continue;
                }
                int x = ai_player.getX();
                int y = ai_player.getY();
                int tox = ThreadLocalRandom.current().nextInt(150);
                int toy =ThreadLocalRandom.current().nextInt(150);
                List<Position> positions = AiMoveCalc(x, y,tox,toy);
                for (Position position : positions) {
                    ReqMultiMoveTo reqMultiMoveTo = new ReqMultiMoveTo();
                    reqMultiMoveTo.setRoleId(roleId);
                    reqMultiMoveTo.setMapId(mapid);
                    reqMultiMoveTo.setDir((short)4);
                    reqMultiMoveTo.setIndex(1);
                    List<Position> list = new ArrayList<>();
                    list.add(position);
                    reqMultiMoveTo.setList(list);
                    IoSession roleSession = SessionUtils.getSessionBy(playerProfile.getGid());
                    fightController.changePosition(roleSession,reqMultiMoveTo);
                    try {
                        sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                ai_player.setX(tox);
                ai_player.setY(toy);
            }
        }finally {
            latch.countDown();
        }
    }
    public void taskAiPlayerMove(IoSession session,int roleId,int type, CountDownLatch latch){
        FightController fightController = SpringUtils.getBean(FightController.class);
        int mapid = 1000;
        try{
            for (int i = 0; i < movePosList.size(); i++) {
                AiPlayer ai_player = (AiPlayer)session.getAttribute("AI_PLAYER");
                PlayerProfile playerProfile = (PlayerProfile)session.getAttribute(SessionProperties.PLAYER);
                Role role = SpringUtils.getRoleService().getOnlinePlayer(playerProfile.getRoleId());
                //log.info("移动AI名称:{}。AI类型：{}",playerProfile.getName(),type);
                if(ai_player == null || ai_player.getOnlineState() == 0){
                    continue;
                }
                int move_pos  =ai_player.getMovepos();
                if(move_pos>=1){
                    List<Position> positions = AiMoveCalc(movePosList.get(move_pos-1).getX(), movePosList.get(move_pos-1).getY(),movePosList.get(move_pos).getX(),movePosList.get(move_pos).getY());
                    for (Position position : positions) {
                        ReqMultiMoveTo reqMultiMoveTo = new ReqMultiMoveTo();
                        reqMultiMoveTo.setRoleId(roleId);
                        reqMultiMoveTo.setMapId(mapid);
                        reqMultiMoveTo.setDir((short)4);
                        reqMultiMoveTo.setIndex(1);
                        List<Position> list = new ArrayList<>();
                        list.add(position);
                        if(move_pos == movePosList.size()-1){
                            Position p = getRandomPos(position);
                            list.add(p);
                        }
                        reqMultiMoveTo.setList(list);
                        IoSession roleSession = SessionUtils.getSessionBy(playerProfile.getGid());
                        fightController.changePosition(roleSession,reqMultiMoveTo);
                        try {
                            if(move_pos == 7){
                                sleep(1800);
                            }else if(move_pos ==2){
                                sleep(1600);
                            }else{
                                sleep(1000);
                            }

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    //到NPC面前停留三秒
                    try {
                        sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    Position newPosition = movePosList.get(move_pos);
                    ReqMultiMoveTo reqMultiMoveTo = new ReqMultiMoveTo();
                    reqMultiMoveTo.setRoleId(roleId);
                    reqMultiMoveTo.setMapId(mapid);
                    reqMultiMoveTo.setDir((short)4);
                    reqMultiMoveTo.setIndex(1);
                    List<Position> list = new ArrayList<>();
                    list.add(newPosition);
                    reqMultiMoveTo.setList(list);
                    IoSession roleSession = SessionUtils.getSessionBy(playerProfile.getGid());
                    fightController.changePosition(roleSession,reqMultiMoveTo);
                    //到NPC面前停留三秒
                    try {
                        sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                if(move_pos ==2 || move_pos ==3 || move_pos == 5 || move_pos == 7){
                    if(move_pos ==3){
                        try {
                            sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    try{
                        /**升级特效局域广播就行 不用全图*/
                        SceneManager.INSTANCE.sendMessages(role, new RespLevelUp(playerProfile.getRoleId(),playerProfile.getLevel()));
                    }catch (Exception e){

                    }

                }
                move_pos+=1;
                if(move_pos >= movePosList.size()){
                    move_pos = 0;
                }
                ai_player.setMovepos(move_pos);
                session.setAttribute("AI_PLAYER",ai_player);
            }
        }finally {
            latch.countDown();
        }
    }

    public void moveTaskAI() {
        log.info("任务AI开始移动");
        while(moveTaskAi){
            int i = 1;
            Random random = new Random();
            CountDownLatch latch = new CountDownLatch(moveTaskAiSessionMap.size());
            for (Map.Entry<Integer, IoSession> sessionMap : moveTaskAiSessionMap.entrySet()) {
                Scheduler2Manager.getInstance().schedule(new Runnable() {
                    @Override
                    public void run() {
                        taskAiPlayerMove(sessionMap.getValue(),sessionMap.getKey(),2,latch);
                    }
                }, i*random.nextInt(2000));
                i+=1;
            }
            try {
                latch.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            try {
                sleep(30000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        log.info("任务AI移动结束");
    }
    public void moveFightAI() {
        log.info("战斗AI开始移动");
        while(moveFightAi){
            int i = 1;
            Random random = new Random();
            for (Map.Entry<Integer, ConcurrentMap<Integer, IoSession>> integerConcurrentMapEntry : fightAiSessionMap.entrySet()) {
                ConcurrentMap<Integer, IoSession> fightMap = integerConcurrentMapEntry.getValue();
                CountDownLatch latch = new CountDownLatch(fightMap.size());
                for (Map.Entry<Integer, IoSession> sessionMap : fightMap.entrySet()) {
                    //发送消息
                    SchedulerManager.getInstance().schedule(new Runnable() {
                        @Override
                        public void run() {
                            fightAiPlayerMove(sessionMap.getValue(),sessionMap.getKey(),5000,latch);
                        }
                    }, i*random.nextInt(300));
                    i+=1;
                }
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        log.info("战斗AI移动结束");
    }
    public Position getRandomPos(Position position){
        Random random = new Random();
        int randomX = random.nextInt(40);
        int randomY = random.nextInt(20);
        int x = position.getX();
        int y = position.getY();
        x = x - 20 + randomX;
        y = y-10 + randomY;
        position.setY((short)y);
        position.setX((short)x);
        return position;
    }
    public void login(IoSession session,int type){
        log.info("登录类型："+type);
        PlayerProfile playerProfile =(PlayerProfile) session.getAttribute(SessionProperties.PLAYER);
        Role role = SpringUtils.getRoleService().getPlayerBy(playerProfile.getRoleId());
        Random random = new Random();
        int x = random.nextInt(20);
        int y = random.nextInt(20);
        int dir = random.nextInt(7);
        if(type == 0){
            Pos pos2 = new Pos();
            {pos2.setX((short)(13+x));pos2.setY((short)(99+y));pos2.setMapId(1000);pos2.setDir((byte)dir);}
            role.setPos(pos2);
        }else{
            x = random.nextInt(200);
            y = random.nextInt(200);
            Pos pos1 = new Pos();
            {pos1.setX((short)(x));pos1.setY((short)(y));pos1.setMapId(5000);pos1.setDir((byte)dir);}
            role.setPos(pos1);
        }
        log.info("初始化假人坐标。。。");
        role.aiSave();
        try {
            sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //请求线路信息；
        ReqRequestLineInfo reqRequestLineInfo = new ReqRequestLineInfo();
        reqRequestLineInfo.setAccountId("110001"+playerProfile.getSid());
        MessagePusher.pushMessage(session,reqRequestLineInfo);
        //登录账号
        ReqLoginAccount reqLoginAccount = new ReqLoginAccount();
        reqLoginAccount.setType("cmd_l_login_AI_player");
        reqLoginAccount.setAccountId("110001"+playerProfile.getSid());
        reqLoginAccount.setPassword("");
        reqLoginAccount.setMac("");
        reqLoginAccount.setData("");
        reqLoginAccount.setLock("");
        reqLoginAccount.setServerName("");
        reqLoginAccount.setChannelId(playerProfile.getDistName());
        reqLoginAccount.setFrom3rdSdk((byte)1);
        reqLoginAccount.setOsVersion("11001");
        reqLoginAccount.setTerm_info("");
        reqLoginAccount.setImei(":1832E02B293D4FF099493BEE3F0CC6471F4BE04EC42DC0D7:");
        reqLoginAccount.setClient_original_ver(":5994E4F13929A3AC982B23BD04CE16B8:");
        reqLoginAccount.setNot_replace((byte)11);
        MessagePusher.pushMessage(session,reqLoginAccount);

        //登录
        ReqLogin reqLogin = new ReqLogin();
        reqLogin.setAccountId("110001"+playerProfile.getSid());
        MessagePusher.pushMessage(session,reqLogin);
        //加载角色
        ReqLoadExistedChar reqLoadExistedChar = new ReqLoadExistedChar();
        reqLoadExistedChar.setChar_name(playerProfile.getName());
        MessagePusher.pushMessage(session,reqLoadExistedChar);
        AiPlayer aiPlayer = new  AiPlayer();
        aiPlayer.setTeamState(0);
        aiPlayer.setOnlineState(1);
        aiPlayer.setMovepos(0);
        session.setAttribute("AI_PLAYER",aiPlayer);
        //发送消息
//        SchedulerManager.getInstance().schedule(new Runnable() {
//            @Override
//            public void run() {
//                initRole(session,playerProfile.getRoleId(),type);
//            }
//        }, 100);
    }
    public void initRole(IoSession session,int roleId,int type){

    }

    public static  List<Position> AiMoveCalc(int startX,int startY,int endX,int endY){
        List<Position> positions = new ArrayList<>();
        int buchang = 12 ;
        int calX = endX- startX;
        int calY = endY - startY;
        int x = calX/buchang;
        int y = calY/buchang;
        List<Integer> listX = new ArrayList<>();
        List<Integer> listY = new ArrayList<>();
        for (int i = 1; i <= Math.abs(x); i++) {
            if(x>0){
                listX.add(startX+(i*buchang));
            }else{
                listX.add(startX-(i*buchang));
            }
        }
        for (int i = 1; i <= Math.abs(y); i++) {
            if(y>0){
                listY.add(startY+(i*buchang));
            }else{
                listY.add(startY-(i*buchang));
            }

        }
        if(listX.size()>listY.size()){
            int posY = endY ;
            for (int i = 0; i < listX.size(); i++) {
                try{
                    posY = listY.get(i);
                }catch(Exception e){
                    posY = endY;
                }
                Position position = new Position((short)listX.get(i).intValue(),(short)posY);
                positions.add(position);
            }
        }else{
            int posX = endX ;
            for (int i = 0; i < listY.size(); i++) {
                try{
                    posX = listX.get(i);
                }catch(Exception e){
                    posX = endX;
                }
                Position position = new Position((short)posX,(short)listY.get(i).intValue());
                positions.add(position);
            }
        }

        positions.add( new Position((short)endX,(short)endY));
        return positions;
    }
}
